
#ifndef _imt_socket_h_
#define _imt_socket_h_

#include "imtPublic.h"
#include "imtLock.h"

#ifdef _iMate_Win
#  ifndef WIN32_LEAN_AND_MEAN
#  define WIN32_LEAN_AND_MEAN
#  endif
#  include <winsock2.h>
#  include <ws2tcpip.h>
#  define socklen_t int
#pragma comment(lib, "WS2_32.lib")
#else
#  include <sys/types.h>
#  include <sys/socket.h>
#  include <signal.h>
#  define closesocket(_x) close(_x)
#  ifndef SOCKET
#    define SOCKET int
#  endif
#  ifndef SOCKET_ERROR
#    define SOCKET_ERROR -1
#  endif
#  ifndef INVALID_SOCKET
#    define INVALID_SOCKET -1
#  endif
#endif

namespace iMate {

	class Socket : public NormalAlloc
	{
	public:
		/**initialise socket system
		@return success to true
		*/
		static bool initSocketSystem();
		/**shut down the socket system
		*/
		static void releaseSocketSystem();

	public:
		///do nothing
		Socket() : mHandle(INVALID_SOCKET)
		{}

		///close socket automatically
		virtual ~Socket()
		{close();}

		/**connect to a specail server
		@param server server address: a numeric host address string 
		  @par dotted-decimal IPv4 address or an IPv6 hex address
	    @param port a numeric string
		@return success to true
		*/
		bool connect(const char* server, const char* port); 

		/*@return success to true*/
		bool disconnect();

		/**send buffer to server without delay
		@param buffer data to be sent
		@param size size of data
		@return size of data sent actually
		  @Note this function will try best to send all data in buffer
		*/
		int send(const char* buffer, int size);

		/**receive data from server
		@param buffer buffer to hold the data from server if any
		@param size the capacity of the buffer passed in
		   @Note size only indicates the capacity of buffer, not means 
		   @par that we'll receive such length of data from server.
	    @return size of data received actually from server
		*/
		int recv(char* buffer, int size);

		///just close the socket
		void close();

	protected:
		///handle identify a native socket
		SOCKET mHandle;
	};

}//iMate











#endif //_imt_socket_h_